package com.irdstudio.apicenter.gateway.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.MaccsPacketUtil;
import com.irdstudio.apicenter.gateway.core.jdbc.MaccsBaseDAO;
import com.irdstudio.apicenter.gateway.util.spring.BeanUtils;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;
/**
 * 移动应用设备登记
 * @author zs.ligm
 * @version 1.0
 * @date 2015-07-24
 */
@Controller
public class DeviceRegister implements IController {

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket,
			HttpServletRequest request, HttpServletResponse response)
			throws MaccsException {

		// 接收移动端传过来的参数
		String appId = inPacket.getValue("appId");
		String deviceId = inPacket.getValue("d");
		String deviceModel = inPacket.getValue("dt");
		String userId = inPacket.getValue("userId");
		String phone = inPacket.getValue("phone");
		String token = inPacket.getValue("token");
		String deviceType = inPacket.getValue("deviceType");
		
		// 是否允许进入应用,默认为否，需管理员在后台审核后通过
		String isAllow = "N";
		
		// 判断必须的参数是否传入
		if (StringUtils.isEmpty(deviceId)) {
			return new JsonView(request, response, MaccsPacketUtil
					.makeFailurePacket("未接收到移动设备号!"));
		}
		if (StringUtils.isEmpty(userId)) {
			return new JsonView(request, response, MaccsPacketUtil
					.makeFailurePacket("未接收到用户编号!"));
		}
		if (StringUtils.isEmpty(phone)) {
			return new JsonView(request, response, MaccsPacketUtil
					.makeFailurePacket("未接收到手机号码!"));
		}
			

		
		// 写入应用移动设备登记表
		MaccsBaseDAO jdbcDao = BeanUtils.getBean(MaccsBaseDAO.class);
		
		//检查是否已登记
		String allow = jdbcDao
				.queryForObject(
						"select is_allow from app_device_register where app_id=? and device_id=?",
						new Object[] { appId, deviceId }, String.class);
		if(!"".equals(allow)){
			return new JsonView(request, response, MaccsPacketUtil
					.makeSimpleSuccessPacket("设备不能重新登记!"));
		}
		//检查是否已登记
		jdbcDao
				.getJdbcTemplate()
				.update(
						"insert into app_device_register(device_id,push_device_id,device_model,device_type,app_id,app_userid,mobile_phone,is_allow) values (?,?,?,?,?,?,?,?)",
						new Object[] { deviceId, token,deviceModel,deviceType, appId,userId,
								phone, isAllow });
		
		// 返回登记结果
		return new JsonView(request, response, MaccsPacketUtil
				.makeSimpleSuccessPacket("设备登记成功!"));
	}

}
